package com.ggh.jinjilive.utils;


import android.text.TextUtils;
import android.util.Base64;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ggh.jinjilive.common.Constants;
import com.ggh.jinjilive.common.MerchantSession;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener1;
import com.ggh.jinjilive.mobile.UserMobile;
import com.ggh.jinjilive.mobile.live.SellGoodsMobile;
import com.ggh.jinjilive.mobile.live.SendGiftMobole;
import com.ggh.jinjilive.mobile.live.im.CommonJson;
import com.ggh.jinjilive.mobile.live.im.CustomMessage;
import com.ggh.jinjilive.mobile.live.im.MessageBaseMobile;
import com.ggh.jinjilive.mobile.live.im.MessageEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMFriendInfo;
import com.tencent.imsdk.v2.V2TIMFriendOperationResult;
import com.tencent.imsdk.v2.V2TIMGroupChangeInfo;
import com.tencent.imsdk.v2.V2TIMGroupListener;
import com.tencent.imsdk.v2.V2TIMGroupMemberChangeInfo;
import com.tencent.imsdk.v2.V2TIMGroupMemberFullInfo;
import com.tencent.imsdk.v2.V2TIMGroupMemberInfo;
import com.tencent.imsdk.v2.V2TIMGroupMemberInfoResult;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMMessageManager;
import com.tencent.imsdk.v2.V2TIMMessageReceipt;
import com.tencent.imsdk.v2.V2TIMSimpleMsgListener;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.imsdk.v2.V2TIMUserInfo;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.Deflater;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class loginIMUtils {

    /**
     * 登录需要设置用户名 userID 和用户签名 userSig，userSig 生成请参考 UserSig 后台 API。
     * @param userid
     * @param usersig
     * @param v2TIMCallback
     */
    public static void loginIM(String userid, String usersig, V2TIMCallback v2TIMCallback){
        V2TIMManager.getInstance().login(userid, usersig, v2TIMCallback);


    }


    /**
     * 退出IM登录
     * @param v2TIMCallback
     */
    public static void logout(V2TIMCallback v2TIMCallback){
        V2TIMManager.getInstance().logout(v2TIMCallback);
    }


    /**
     * 修改个人资料
     * @param info
     */
    public static void setSelfInfo(V2TIMUserFullInfo info)	{
        V2TIMManager.getInstance().setSelfInfo(info, new V2TIMCallback() {
            @Override
            public void onSuccess() {
                ToastUtils.make().show("聊天资料修改成功");
            }

            @Override
            public void onError(int code, String desc) {
                ToastUtils.make().show(code+ "聊天资料修改失败" + desc);
            }
        });
    }


    /**
     * 屏蔽某人的消息（添加该用户到黑名单中）
     */
    public static void addToBlackList(List<String> userIDList,	V2TIMValueCallback<List<V2TIMFriendOperationResult>> callback){
        V2TIMManager.getFriendshipManager().addToBlackList(userIDList,callback);
    }

    /**
     * 把用户从黑名单中删除
     * @param userIDList
     * @param callback
     */
    public static void deleteFromBlackList(List<String> userIDList,	V2TIMValueCallback<List<V2TIMFriendOperationResult>> callback){
        V2TIMManager.getFriendshipManager().deleteFromBlackList(userIDList,callback);
    }

    /**
     * 获取黑名单列表
     * @param callback
     */
    public static void getBlackList(V2TIMValueCallback<List<V2TIMFriendInfo>> callback){
        V2TIMManager.getFriendshipManager().getBlackList(callback);
    }


    /**
     *  创建群组
     * @param room_id
     * @param groupNamem
     */
    public static void createGroup(final String room_id, final String groupNamem){
        V2TIMManager.getInstance().createGroup("AVChatRoom",room_id,groupNamem,null);
    }

    /**
     * Work：任何人都无法解散群组。
     * 其他群：群主可以解散群组。
     * @param groupID
     * @param callback
     */
    public static void dismissGroup(String groupID,final V2TIMCallback callback){
        V2TIMManager.getInstance().dismissGroup(groupID,callback);
    }

    /**
     * 发送IM群文本消息
     * @param text
     * @param groupID
     * @param callback
     */
    public static void sendGroupTextMessage(String text, String groupID, V2TIMValueCallback<V2TIMMessage> callback){
        V2TIMManager.getInstance().sendGroupTextMessage(text, groupID, V2TIMMessage.V2TIM_PRIORITY_NORMAL, callback);
    }

    /**
     * 发送CC（端到端）自定义消息
     * @param bytes
     * @param toUserID
     */
    public static void sendC2CCustomMessage(byte[] bytes,String toUserID){
        V2TIMManager.getInstance().sendC2CCustomMessage(bytes, toUserID, new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
            }

            @Override
            public void onError(int code, String desc) {
            }
        });
    }


    /**
     * 进入直播间
     * @param userMobile
     */
    public static void setEnterTheStudio(UserMobile userMobile, String groupID, AddOnClickListener1 addOnClickListener1){
        //
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMessage("进入直播间");
        messageEntity.setNickname(userMobile.getNickname());
        messageEntity.setRank(userMobile.getLevel());
        messageEntity.setLevel_img(userMobile.getLevel_img());
        messageEntity.setAvatar(MerchantSession.getInstance().getUser().getHead_portrait());
        //
        CommonJson<CustomMessage> customMessage = new CommonJson<>();
        customMessage.cmd = "CustomCmdMsg";
        customMessage.data = new CustomMessage();
        customMessage.data.userName = MerchantSession.getInstance().getUser().getNickname();
        customMessage.data.userAvatar = MerchantSession.getInstance().getUser().getHead_portrait();
        customMessage.data.cmd = "2";
        customMessage.data.msg = new Gson().toJson(messageEntity);
        //
        final String content = new Gson().toJson(customMessage, new TypeToken<CommonJson<CustomMessage>>() {}.getType());
        //发送消息
        V2TIMManager.getInstance().sendGroupCustomMessage(content.getBytes(), groupID, V2TIMMessage.V2TIM_PRIORITY_NORMAL, new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                if(null != addOnClickListener1){
                    CustomMessage customMessage1 = new CustomMessage();
                    customMessage1.cmd = "2";
                    customMessage1.msg = new Gson().toJson(messageEntity);
                    addOnClickListener1.onSkipClicked(customMessage1);
                }
            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }

    /**
     * 退出直播间
     * @param userMobile
     * @param groupID
     * @param addOnClickListener1
     */
    public static void setExitStudio(UserMobile userMobile, String groupID, AddOnClickListener1 addOnClickListener1){
        //
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMessage("退出直播间");
        messageEntity.setNickname(userMobile.getNickname());
        messageEntity.setRank(userMobile.getLevel());
        messageEntity.setLevel_img(userMobile.getLevel_img());
        //
        CommonJson<CustomMessage> customMessage = new CommonJson<>();
        customMessage.cmd = "CustomCmdMsg";
        customMessage.data = new CustomMessage();
        customMessage.data.userName = MerchantSession.getInstance().getUser().getNickname();
        customMessage.data.userAvatar = MerchantSession.getInstance().getUser().getHead_portrait();
        customMessage.data.cmd = "3";
        customMessage.data.msg = new Gson().toJson(messageEntity);
        //
        final String content = new Gson().toJson(customMessage, new TypeToken<CommonJson<CustomMessage>>() {}.getType());
        //发送消息
        V2TIMManager.getInstance().sendGroupCustomMessage(content.getBytes(), groupID, V2TIMMessage.V2TIM_PRIORITY_NORMAL, new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                if(null != addOnClickListener1){
                    addOnClickListener1.onSkipClicked("发送成功");
                }
            }

            @Override
            public void onError(int code, String desc) {
                if(null != addOnClickListener1){
                    addOnClickListener1.onSkipClicked("发送成功");
                }
            }
        });
    }

    /**
     * 发送礼物
     * @param sendGiftMobole
     * @param groupID
     * @param addOnClickListener1
     */
    public static void sendGift(SendGiftMobole sendGiftMobole,String groupID, AddOnClickListener1 addOnClickListener1){
        //
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMessage(new Gson().toJson(sendGiftMobole));
        messageEntity.setNickname(MerchantSession.getInstance().getUser().getNickname());
        messageEntity.setRank(MerchantSession.getInstance().getUser().getLevel());
        messageEntity.setLevel_img(MerchantSession.getInstance().getUser().getLevel_img());
        //
        CommonJson<CustomMessage> customMessage = new CommonJson<>();
        customMessage.cmd = "CustomCmdMsg";
        customMessage.data = new CustomMessage();
        customMessage.data.userName = MerchantSession.getInstance().getUser().getNickname();
        customMessage.data.userAvatar = MerchantSession.getInstance().getUser().getHead_portrait();
        customMessage.data.cmd = "8";
        customMessage.data.msg = new Gson().toJson(messageEntity);
        //
        final String content = new Gson().toJson(customMessage, new TypeToken<CommonJson<CustomMessage>>() {}.getType());
        //发送消息
        V2TIMManager.getInstance().sendGroupCustomMessage(content.getBytes(), groupID, V2TIMMessage.V2TIM_PRIORITY_NORMAL, new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                if(null != addOnClickListener1){
                    addOnClickListener1.onSkipClicked("发送成功");
                }
            }

            @Override
            public void onError(int code, String desc) {
                if(null != addOnClickListener1){
                    addOnClickListener1.onSkipClicked("发送成功");
                }
            }
        });
    }

    /**
     * 发送开始带货
     * @param sellGoodsMobile
     * @param groupID
     */
    public static void sendSellGoods(SellGoodsMobile sellGoodsMobile,String groupID){
        //
        CommonJson<CustomMessage> customMessage = new CommonJson<>();
        customMessage.cmd = "CustomCmdMsg";
        customMessage.data = new CustomMessage();
        customMessage.data.userName = MerchantSession.getInstance().getUser().getNickname();
        customMessage.data.userAvatar = MerchantSession.getInstance().getUser().getHead_portrait();
        customMessage.data.cmd = "20";
        customMessage.data.msg = new Gson().toJson(sellGoodsMobile);
        //
        final String content = new Gson().toJson(customMessage, new TypeToken<CommonJson<CustomMessage>>() {}.getType());
        LogUtils.d("发送带货" + content);
        //发送消息
        V2TIMManager.getInstance().sendGroupCustomMessage(content.getBytes(), groupID, V2TIMMessage.V2TIM_PRIORITY_NORMAL, null);

    }

    /**
     * 发送结束带货
     * @param groupID
     */
    public static void finishSellGoods(String groupID){
        //
        CommonJson<CustomMessage> customMessage = new CommonJson<>();
        customMessage.cmd = "CustomCmdMsg";
        customMessage.data = new CustomMessage();
        customMessage.data.userName = MerchantSession.getInstance().getUser().getNickname();
        customMessage.data.userAvatar = MerchantSession.getInstance().getUser().getHead_portrait();
        customMessage.data.cmd = "21";
        //
        final String content = new Gson().toJson(customMessage, new TypeToken<CommonJson<CustomMessage>>() {}.getType());
        LogUtils.d("发送带货" + content);
        //发送消息
        V2TIMManager.getInstance().sendGroupCustomMessage(content.getBytes(), groupID, V2TIMMessage.V2TIM_PRIORITY_NORMAL, null);

    }


    /**
     * 发送群聊自定义（信令）
     * @param groupID
     * @param callback
     */
    public static void sendGroupCustomMessage(String cmd, String message,String groupID,V2TIMValueCallback<V2TIMMessage> callback){
        CommonJson<CustomMessage> customMessage = new CommonJson<>();
        customMessage.cmd = "CustomCmdMsg";
        customMessage.data = new CustomMessage();
        customMessage.data.userName = MerchantSession.getInstance().getUser().getNickname();
        customMessage.data.userAvatar = MerchantSession.getInstance().getUser().getHead_portrait();
        customMessage.data.cmd = cmd;
        customMessage.data.msg = message;
        final String content = new Gson().toJson(customMessage, new TypeToken<CommonJson<CustomMessage>>() {}.getType());
        LogUtils.d("发送消息" + content);
        V2TIMManager.getInstance().sendGroupCustomMessage(content.getBytes(),groupID,V2TIMMessage.V2TIM_PRIORITY_NORMAL,callback);
    }

    /**
     * 	设置基本消息（文本消息和自定义消息）的事件监听器，
     * 请不要同 addAdvancedMsgListener 混用。
     * @param
     */
    public static void addSimpleMsgListener(AddItemOnClickListener addItemOnClickListener){

        V2TIMManager.getInstance().addSimpleMsgListener(new V2TIMSimpleMsgListener() {
            @Override
            public void onRecvC2CTextMessage(String msgID, V2TIMUserInfo sender, String text) {
                super.onRecvC2CTextMessage(msgID, sender, text);
                //收到 C2C 文本消息
                LogUtils.d(text);
            }

            @Override
            public void onRecvC2CCustomMessage(String msgID, V2TIMUserInfo sender, byte[] customData) {
                super.onRecvC2CCustomMessage(msgID, sender, customData);

                //收到 C2C 自定义（信令）消息
                String text = new String(customData);
                LogUtils.d("收到 C2C 自定义（信令）消息" + text);
                addItemOnClickListener.onSkipClicked(2,customData);
            }

            @Override
            public void onRecvGroupTextMessage(String msgID, String groupID, V2TIMGroupMemberInfo sender, String text) {
                super.onRecvGroupTextMessage(msgID, groupID, sender, text);
                //收到群文本消息
                String[] strings = text.split("<@#>");
                addItemOnClickListener.onSkipClicked(0,strings);
            }

            @Override
            public void onRecvGroupCustomMessage(String msgID, String groupID, V2TIMGroupMemberInfo sender, byte[] customData) {
                super.onRecvGroupCustomMessage(msgID, groupID, sender, customData);
                //收到群自定义（信令）消息
                String customStr = new String(customData);
                LogUtils.d("收到群自定义（信令）消息" + customStr);
                CommonJson commonJson = new Gson().fromJson(customStr,CommonJson.class);
                if(commonJson.cmd.equals("notifyPusherChange")){// {"cmd":"notifyPusherChange","data":{"userID":"16"}}
                    return;
                }

                CustomMessage customMessage = new Gson().fromJson(new Gson().toJson(commonJson.data), CustomMessage.class);
                if(customMessage.cmd.equals("20")){
                    SellGoodsMobile sellGoodsMobile = new Gson().fromJson(customMessage.msg,SellGoodsMobile.class);
                    addItemOnClickListener.onSkipClicked(20,sellGoodsMobile);
                    return;
                }else if(customMessage.cmd.equals("21")){
                    addItemOnClickListener.onSkipClicked(21,customMessage);
                    return;
                }
                addItemOnClickListener.onSkipClicked(1,customMessage);
            }
        });
    }


    /**
     * 设置群组相关的事件监听器
     * @param addItemOnClickListener
     */
    public static void setGroupListener(AddItemOnClickListener addItemOnClickListener){
        V2TIMManager.getInstance().setGroupListener(new V2TIMGroupListener() {
            @Override
            public void onReceiveRESTCustomData(String groupID, byte[] customData) {
                super.onReceiveRESTCustomData(groupID, customData);
                //收到 RESTAPI 下发的自定义系统消息
                String customStr = new String(customData);
                MessageBaseMobile messageBaseMobile = new Gson().fromJson(customStr,MessageBaseMobile.class);
                if(null != addItemOnClickListener){
                    addItemOnClickListener.onSkipClicked(messageBaseMobile.getType(),customStr);
                }
            }

            @Override
            public void onGroupDismissed(String groupID, V2TIMGroupMemberInfo opUser) {
                super.onGroupDismissed(groupID, opUser);
                if(null != addItemOnClickListener){
                    addItemOnClickListener.onSkipClicked(1001,"群被解散了");
                }
            }
        });
    }

    /**
     * 高级消息收发接口
     */
    public static void addAdvancedMsgListener(AddItemOnClickListener addItemOnClickListener){
        V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {//收到新消息
                super.onRecvNewMessage(msg);
                if(null != addItemOnClickListener){
                    addItemOnClickListener.onSkipClicked(0,msg);
                }
            }

            @Override
            public void onRecvC2CReadReceipt(List<V2TIMMessageReceipt> receiptList) {//收到 C2C 消息已读回执
                super.onRecvC2CReadReceipt(receiptList);
            }

            @Override
            public void onRecvMessageRevoked(String msgID) {//收到消息撤回的通知
                super.onRecvMessageRevoked(msgID);
            }
        });
    }


    /**
     * 加入群组
     * @param callback
     */
    public static void joinGroup(String groupID,V2TIMCallback callback){
        V2TIMManager.getInstance().joinGroup(groupID,"",callback);
    }

    /**
     * 退出群组
     * @param groupID
     * @param callback
     */
    public static void quitGroup(String groupID,final V2TIMCallback callback){
        V2TIMManager.getInstance().quitGroup(groupID,callback);
    }


    /**
     *获取群成员列表
     * @param groupID
     */
    public static void getGroupMemberList(String groupID, V2TIMValueCallback<V2TIMGroupMemberInfoResult> callback ){
        V2TIMManager.getGroupManager().getGroupMemberList(groupID, V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_FILTER_ALL, 0,callback);
    }

    /**
     * 获取指定群在线人数
     * @param groupID
     */
    public static void getGroupOnlineMemberCount(String groupID){
        V2TIMManager.getGroupManager().getGroupOnlineMemberCount(groupID, new V2TIMValueCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                LogUtils.d("人数" + integer);
            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }

    /**
     * 获取指定的群成员资料
     * @param groupID
     * @param memberList
     * @param callback
     */
    public static void getGroupMembersInfo(String groupID, List<String> memberList,V2TIMValueCallback<List<V2TIMGroupMemberFullInfo>> callback){
        V2TIMManager.getGroupManager().getGroupMembersInfo(groupID,memberList,callback);
    }

    /**
     * 签名过期时间，建议不要设置的过短
     * <p>
     * 时间单位：秒
     * 默认时间：7 x 24 x 60 x 60 = 604800 = 7 天
     */
    private static final int EXPIRETIME = 604800;

    /**
     * 计算签名用的加密密钥，获取步骤如下：
     * <p>
     * step1. 进入腾讯云云通信[控制台](https://console.cloud.tencent.com/avc ) ，如果还没有应用就创建一个，
     * step2. 单击“应用配置”进入基础配置页面，并进一步找到“帐号体系集成”部分。
     * step3. 点击“查看密钥”按钮，就可以看到计算 UserSig 使用的加密的密钥了，请将其拷贝并复制到如下的变量中
     * <p>
     * 注意：该方案仅适用于调试Demo，正式上线前请将 UserSig 计算代码和密钥迁移到您的后台服务器上，以避免加密密钥泄露导致的流量盗用。
     * 文档：https://cloud.tencent.com/document/product/269/32688#Server
     */
    private static final String SECRETKEY = "2f7cbd9e7634f87b307693135949d250316fc2a027366ff892de6622e81909d9";

    /**
     * 计算 UserSig 签名
     * <p>
     * 函数内部使用 HMAC-SHA256 非对称加密算法，对 SDKAPPID、userId 和 EXPIRETIME 进行加密。
     *
     * @note: 请不要将如下代码发布到您的线上正式版本的 App 中，原因如下：
     * <p>
     * 本文件中的代码虽然能够正确计算出 UserSig，但仅适合快速调通 SDK 的基本功能，不适合线上产品，
     * 这是因为客户端代码中的 SECRETKEY 很容易被反编译逆向破解，尤其是 Web 端的代码被破解的难度几乎为零。
     * 一旦您的密钥泄露，攻击者就可以计算出正确的 UserSig 来盗用您的腾讯云流量。
     * <p>
     * 正确的做法是将 UserSig 的计算代码和加密密钥放在您的业务服务器上，然后由 App 按需向您的服务器获取实时算出的 UserSig。
     * 由于破解服务器的成本要高于破解客户端 App，所以服务器计算的方案能够更好地保护您的加密密钥。
     * <p>
     * 文档：https://cloud.tencent.com/document/product/269/32688#Server
     */
    public static String genTestUserSig(String userId) {
        return GenTLSSignature(Constants.SDKAppID, userId, EXPIRETIME, null, SECRETKEY);
    }


    /**
     * 生成 tls 票据
     *
     * @param sdkappid      应用的 appid
     * @param userId        用户 id
     * @param expire        有效期，单位是秒
     * @param userbuf       默认填写null
     * @param priKeyContent 生成 tls 票据使用的私钥内容
     * @return 如果出错，会返回为空，或者有异常打印，成功返回有效的票据
     */
    private static String GenTLSSignature(long sdkappid, String userId, long expire, byte[] userbuf, String priKeyContent) {
        if (TextUtils.isEmpty(priKeyContent)) {
            return "";
        }
        long       currTime = System.currentTimeMillis() / 1000;
        JSONObject sigDoc   = new JSONObject();
        try {
            sigDoc.put("TLS.ver", "2.0");
            sigDoc.put("TLS.identifier", userId);
            sigDoc.put("TLS.sdkappid", sdkappid);
            sigDoc.put("TLS.expire", expire);
            sigDoc.put("TLS.time", currTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String base64UserBuf = null;
        if (null != userbuf) {
            base64UserBuf = Base64.encodeToString(userbuf, Base64.NO_WRAP);
            try {
                sigDoc.put("TLS.userbuf", base64UserBuf);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String sig = hmacsha256(sdkappid, userId, currTime, expire, priKeyContent, base64UserBuf);
        if (sig.length() == 0) {
            return "";
        }
        try {
            sigDoc.put("TLS.sig", sig);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Deflater compressor = new Deflater();
        compressor.setInput(sigDoc.toString().getBytes(Charset.forName("UTF-8")));
        compressor.finish();
        byte[] compressedBytes = new byte[2048];
        int compressedBytesLength = compressor.deflate(compressedBytes);
        compressor.end();
        return new String(base64EncodeUrl(Arrays.copyOfRange(compressedBytes, 0, compressedBytesLength)));
    }


    private static String hmacsha256(long sdkappid, String userId, long currTime, long expire, String priKeyContent, String base64Userbuf) {
        String contentToBeSigned = "TLS.identifier:" + userId + "\n"
                + "TLS.sdkappid:" + sdkappid + "\n"
                + "TLS.time:" + currTime + "\n"
                + "TLS.expire:" + expire + "\n";
        if (null != base64Userbuf) {
            contentToBeSigned += "TLS.userbuf:" + base64Userbuf + "\n";
        }
        try {
            byte[] byteKey = priKeyContent.getBytes("UTF-8");
            Mac hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA256");
            hmac.init(keySpec);
            byte[] byteSig = hmac.doFinal(contentToBeSigned.getBytes("UTF-8"));
            return new String(Base64.encode(byteSig, Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            return "";
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (InvalidKeyException e) {
            return "";
        }
    }


    private static byte[] base64EncodeUrl(byte[] input) {
        byte[] base64 = new String(Base64.encode(input, Base64.NO_WRAP)).getBytes();
        for (int i = 0; i < base64.length; ++i)
            switch (base64[i]) {
                case '+':
                    base64[i] = '*';
                    break;
                case '/':
                    base64[i] = '-';
                    break;
                case '=':
                    base64[i] = '_';
                    break;
                default:
                    break;
            }
        return base64;
    }
}
